<?php
echo $this->headScript()->setFile($this->baseUrl().'/js/jquery/table-sorter/jquery.dataTables.js');
$mem_db 	= 	new Members_Model_DbTable_MemberList();
$tableLists = 	$mem_db->getAdapter()->listTables();
$form_db 	= 	new Members_Model_DbTable_Forms();
$formLists	=	$form_db->getAllForms();
$permission_arr = array('export_enable' => $this->allow('export','csv','Database'), 'import1_enable' => $this->allow('import','csv','Database'), 'delete_enable' => $this->allow('delete','csv','Database'));

if (!$this->allow('list')) : ?>
	<div class="grid_12 t_a_bottom">
		<?php echo $this->translator->translator('Member_Access_deny_desc'); ?>
	</div>
<?php else : ?>
<script type="text/javascript">
$(document).ready(function() {
	floatingbar('#floatingbar',"#button_top_bar",null);
	/****************************Sorting Table Start*********************/
	var oTable = $("#sortTable").dataTable({
				"bPaginate": false,
				"bLengthChange": true,
				"bSearchable": true,
				"bFilter": true,
				"bSort": true,
				"bInfo": false,
				"bAutoWidth": true,
				"bProcessing": false,
				"bSortClasses": true,
				"bStateSave": false,
				"bServerSide": false,
				"aaSorting": [[ 1, "desc" ]],				
				"aoColumnDefs": [ 
						{ "bSortable": false, "bSortClasses": false,  "aTargets": [ 0 ] }
					],
				"oLanguage" : { "sSearch": "<?php echo $this->translator->translator('jquery_filter'); ?>" }
			}); 	
	
	$('td', oTable.fnGetNodes()).hover( function() {		
		$(this).parents("tr:first").children('td').addClass( 'highlighted' );
	}, function() {
		$('td.highlighted').removeClass('highlighted');
	});
	
	/****************************Sorting Table End*********************/
	$('a.export_btn').click(function() {
		var self = this;
		var post_type = $(self).attr('rel');
		var table_name = $(self).parents("span:first").parents("div:first").parents("div:first").children("div:nth-child(2)").children("select:first").val();		
		
		$.ajax({
					url: "<?php echo $this->url( array('module'=> 'Database', 'controller' => 'csv', 'action'     => 'export' ), 'adminrout',    true) ?>",
					type: 'POST',
					data: {post_type : post_type, table_name : table_name},
					beforeSend: function(){
						$(self).html('<span class="icon loader"></span>');
					 },
					success: function(response) 
					{
						//alert(response);
						var json_arr = eval("("+response+")");
						if(json_arr.status == 'ok')
						{							
							putResult(json_arr.data,oTable);
							openMsgDialog(json_arr.msg);
						}
						else
						{							
							openMsgDialog(json_arr.msg);
						}
						$(self).html("<span class='icon submit'><?php echo $this->translator->translator('common_export'); ?></span>");							
					},
					error: function(xhr, status, error){				
						var msg = "Error! " + xhr.status + " " + error;
						openMsgDialog(msg);
						$(self).html("<span class='icon submit'><?php echo $this->translator->translator('common_export'); ?></span>");	
					}
			});
	});	
	
	$('a.delete_all').click(function() {
		var self = this;
		if($('input.check_btn:checked').length > 0)
		{
			$("#dialog-confirm").html('<span class="icon submit"><?php echo addslashes($this->translator->translator('database_file_delete_confirm')); ?></span>').dialog({
					resizable: false,
					width:400,
					height:170,
					modal: true,
					show: 'fade',
					hide: 'explode',
					buttons: {
							'<?php echo html_entity_decode($this->translator->translator("common_delete_selected"), ENT_QUOTES, "UTF-8"); ?>': function() {
							deleteAll(self);
							$(this).dialog('close');
						},
					'<?php echo html_entity_decode($this->translator->translator("common_cancel"), ENT_QUOTES, "UTF-8"); ?>': function() {
							$(this).dialog('close');
						}
					}
				});		
		}
		else
		{
			var msg = "<?php echo $this->translator->translator('common_selected_err'); ?>";
			openMsgDialog(msg);
		}
	});	
	
	$('input.checkAll_btn').click(function() {
		var self = this;
		if($(self).is(':checked'))
		{		
			$('input.check_btn').attr('checked', true);
		}
		else
		{
			$('input.check_btn').attr('checked', false);
		}
	});	
	
	allFunction();
	
});

function putResult(template_info,oTable)
{		
	var img_html	=	'<a href="'+template_info.path+'/'+template_info.name+'">'+template_info.name+'</a>';

	var actionColumn =	'<ul>'+
							'<li>'+
									<?php if ($permission_arr['import_enable']) : ?>
										'<a href="javascript:void(0);" rel="'+template_info.name+'" class="restore_btn" ><img src="application/modules/Administrator/layouts/scripts/images/tools/restore.png"  border="0" title="<?php echo $this->translator->translator("common_restore"); ?>" /></a>'+
									<?php endif; ?>
							'</li>'+													
							'<li>'+
									<?php if ($permission_arr['delete_enable']) : ?>
									'<a href="javascript:void(0);" class="delete_btn"  rel="'+template_info.name+'"><img src="application/modules/Administrator/layouts/scripts/images/tools/delete.png" title="<?php echo $this->translator->translator("common_delete_title"); ?>" border="0" /></a>'+
									<?php endif; ?>	
							'</li>'+
						'</ul>';
	oTable.fnAddData([
				'<input type="checkbox" name="checkbtn" id="checkbtn" value="'+template_info.name+'" class="check_btn" />',				
				img_html,
				actionColumn
				 ]);
	$('td', oTable.fnGetNodes()).hover( function() {		
		$(this).parents("tr:first").children('td').addClass( 'highlighted' );
	}, function() {
		$('td.highlighted').removeClass('highlighted');
	});
	
	$('td', oTable.fnGetNodes()).parents("tr:first").parents("tbody:first").children('tr').children('td:nth-child(1)').addClass('center');	
	$('td', oTable.fnGetNodes()).parents("tr:first").parents("tbody:first").children('tr').children('td:nth-child(3)').addClass('tools-list');
	allFunction();
}	

/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
	var aReturn = new Array();
	var aTrs = oTableLocal.fnGetNodes();
	
	for ( var i=0 ; i<aTrs.length ; i++ )
	{
		if ( $(aTrs[i]).hasClass('row_selected') )
		{
			aReturn.push( aTrs[i] );
		}
	}
	return aReturn;
}

function openMsgDialog(msg)
{
	$('#dialog_msg').html(msg).dialog({
		autoOpen: true,
		modal: false,
		width: 'auto',
		height: 'auto',
		show: 'fade',
		resizable: 'false',				
		buttons: { "<?php echo html_entity_decode($this->translator->translator('common_ok'), ENT_QUOTES, 'UTF-8'); ?>": function() { $(this).dialog('option', 'hide', 'explode').dialog("close"); } },
		open: function(event, ui)
			 {
				setTimeout(function() 
				{									
					if($('#' + event.target.id).dialog('isOpen'))
					{
						$('#' + event.target.id).dialog('option', 'hide', 'explode').dialog('close');										
					}
				}, 10000);
			  }
	});
}

function inputRestore()
{	
	var input = '<table width="100%" border="0" align="center" cellpadding="0" cellspacing="5">'+
					'<tr>'+
						'<td colspan="2" id="main_err" align="center"></td>'+
					'</tr>'+
					'<tr>'+
					  '<td width="50%" height="22" ><?php echo addslashes($this->translator->translator("database_host_name")); ?></td>'+
					  '<td width="50%">'+
					  '<input type="text" size="20" name="host_name" id="host_name" />&nbsp;<br /><span id="host_name_err"></span>'+					  
					  '</td>'+
					'</tr>'+
					'<tr>'+
					  '<td height="22"><?php echo addslashes($this->translator->translator("database_user_name")); ?></td>'+
					  '<td>'+
					  '<input type="text" size="20" name="user_name" id="user_name" />&nbsp;<br /><span id="user_name_err"></span>'+					  
					  '</td>'+
					'</tr>'+
					'<tr>'+
					  '<td height="22"><?php echo addslashes($this->translator->translator("database_user_password")); ?></td>'+
					  '<td>'+
					  '<input type="text" size="20"  name="user_password" id="user_password" />&nbsp;<br /><span id="user_password_err"></span>'+					  
					  '</td>'+
					'</tr>'+
					'<tr>'+
					  '<td height="22"><?php echo addslashes($this->translator->translator("database_db_name")); ?></td>'+
					  '<td>'+
					  '<input type="text" size="20"  name="db_name" id="db_name" />&nbsp;<br /><span id="db_name_err"></span>'+					  
					  '</td>'+
					'</tr>'+
				  '</table>';
	return input;
}

function clearError()
{
	$('#host_name_err').html('');
	$('#user_name_err').html('');
	$('#db_name_err').html('');
	$('#main_err').html('');
}

function deleteAll(self)
{
	var id_str = '';
	for(var i=0;i < $('input.check_btn:checked').length;i++)
	{
		if(i == 0)
		{
			 id_str += $('input.check_btn:checked:eq('+i+')').val();
		}
		else
		{
			id_str += ','+$('input.check_btn:checked:eq('+i+')').val();
		}
	}
	
	$.ajax({
			url: "<?php echo $this->url( array('module'=> 'Database', 'controller' => 'csv', 'action'     => 'deleteall' ), 'adminrout',    true) ?>",
			type: 'POST',
			data: { id_st: id_str},
			beforeSend: function(){
				$(self).html('<span class="icon loader"></span>');
			 },
			success: function(response) 
			{
				//alert(response);
				var json_arr = eval("("+response+")");
				if(json_arr.status == 'ok')
				{
					for(var i= ($('input.check_btn:checked').length-1);i >= 0;i--)
					{								
						$('input.check_btn:checked:eq('+i+')').parents("td:first").parents("tr:first").addClass('row_selected');																			
					}
					var oTabled = $('#sortTable').dataTable();
					var anSelected = fnGetSelected( oTabled );
					for(var k = 0; k < anSelected.length; k++)
					{
						oTabled.fnDeleteRow( anSelected[k] );
					}
				}
				else
				{							
					openMsgDialog(json_arr.msg);
				}	
				$(self).html('<span class="icon delete"><?php echo html_entity_decode($this->translator->translator("common_delete_selected"), ENT_QUOTES, "UTF-8"); ?></span>');
			},
			error: function(xhr, status, error){
				var msg = "Error! " + xhr.status + " " + error;
				openMsgDialog(msg);
			}
	});	
}

function deleteThis(self)
{
	var file_name = $(self).attr('rel');
	$.ajax({
		 url: "<?php echo $this->url( array('module'=> 'Database', 'controller' => 'csv', 'action'     => 'delete' ), 'adminrout',    true) ?>",
		 type: 'POST',
		 data: { file_name: file_name },
		 beforeSend: function(){
				$(self).html('<img src="application/modules/Administrator/layouts/scripts/images/loader/ajax_loader.gif" height="16" border="0" />');
			 },
		 success: function(response) 
		 {
			//alert(response);
			var json_arr = eval("("+response+")");
			if(json_arr.status == 'ok')
			{
				$(self).parents("li:first").parents("ul:first").parents("td:first").parents("tr:first").addClass('row_selected');
				var oTables = $('#sortTable').dataTable();
				var anSelected = fnGetSelected( oTables );
				oTables.fnDeleteRow( anSelected[0] );
			}
			else
			{
				openMsgDialog(json_arr.msg);
			}
		 },
		error: function(xhr, status, error){
			var msg = "Error! " + xhr.status + " " + error;
			openMsgDialog(msg);
		}
	});
}


function allFunction()
{
	$('a.restore_btn').unbind('click');
	$('a.restore_btn').click(function() {
		var self = this;
		var inputHtml = inputRestore();		
		$("#restore-confirm").html(inputHtml).dialog({
			resizable: true,
			width:500,
			//height:225,
			modal: true,
			show: 'fade',
			hide: 'explode',
			buttons: {
						'<?php echo $this->translator->translator("database_restore_do"); ?>': function() {
									var file_name = $(self).attr('rel');
									var host_name = $('#host_name').val();
									var user_name = $('#user_name').val();
									var user_password = $('#user_password').val();
									var db_name = $('#db_name').val();
									clearError();
									if(host_name != '' && user_name != '' && db_name != '' && file_name != '')
									{
										$(this).dialog('close');
										$.ajax({
												url: "<?php echo $this->url( array('module'=> 'Database', 'controller' => 'backend', 'action'     => 'restore' ), 'adminrout',    true) ?>",
												type: 'POST',
												data: { file_name: file_name, host_name: host_name, user_name: user_name, user_password: user_password, db_name: db_name },
												beforeSend: function(){
													$(self).html('<img src="application/modules/Administrator/layouts/scripts/images/loader/ajax_loader.gif" height="16" border="0" />');
												 },
												success: function(response) 
												{
													//alert(response);
													var json_arr = eval("("+response+")");
													if(json_arr.status == 'ok')
													{	
														openMsgDialog(json_arr.msg);
													}
													else
													{							
														openMsgDialog(json_arr.msg);
													}
													$(self).html('<img src="application/modules/Administrator/layouts/scripts/images/tools/restore.png" title="<?php echo $this->translator->translator("common_restore"); ?>" width="22" height="28" border="0" />');							
												}
										});
									}
									else
									{
										if(host_name == '')
										{
											$('#host_name_err').html('<?php echo $this->translator->translator("database_host_name_err"); ?>');
										}
										if(user_name == '')
										{
											$('#user_name_err').html('<?php echo $this->translator->translator("database_user_name_err"); ?>');
										}
										if(db_name == '')
										{
											$('#db_name_err').html('<?php echo $this->translator->translator("database_db_name_err"); ?>');
										}
										if(file_name == '')
										{
											$('#main_err').html('<?php echo $this->translator->translator("database_file_name_err"); ?>');
										}
									}									
								},
						Cancel: function() {
								$(this).dialog('close');
								}
					}
		});
	});
	
	$('a.delete_btn').unbind('click');
	$('a.delete_btn').click(function() {
		var self = this;
		$("#dialog-confirm").html("<?php echo addslashes($this->translator->translator('database_file_delete_confirm')); ?>").dialog({
			resizable: false,
			width:400,
			height:170,
			modal: true,
			show: 'fade',
			hide: 'explode',
			buttons: {
					'<?php echo html_entity_decode($this->translator->translator("common_delete"), ENT_QUOTES, "UTF-8"); ?>': function() {
					deleteThis(self);
					$(this).dialog('close');
				},
			'<?php echo html_entity_decode($this->translator->translator("common_cancel"), ENT_QUOTES, "UTF-8"); ?>': function() {
					$(this).dialog('close');
				}
			}
		});		
	});
}
</script>

<div id="container">
<div class="title-container">
	<div class="database-export-import"><h1><?php echo $this->translator->translator('database_csv_page_name'); ?></h1></div>
    
    <div class="button-container">
    	
        
        <?php  if ($permission_arr['delete_enable']) : ?>
        <span class="button  ui-widget-content-1"><a href="javascript: void(0);" class="delete_all"><span class="icon delete"><?php echo html_entity_decode($this->translator->translator("common_delete_selected"), ENT_QUOTES, "UTF-8"); ?></span></a></span>
        <?php endif; ?>
    </div>
</div>
<div id="button_top_bar"></div>
<div class="content-container">
	<div id="sidebar-inner">
    	<?php echo $this->partial('nav_menu.phtml');  ?>
    </div>
    
    
    
    <div id="content-inner">
    
    	<div class="toggle-container">         	
                <div class="toggle-search">
                
                	<!-- Row 1 Start -->
                    <div class="toggle-row">
                        <div class="toggle-label">
                            <span class="label"><?php echo $this->translator->translator('database_list_page_export_db'); ?></span>
                        </div>
                        
                        <div class="toggle-field" style="vertical-align:middle;">
                           <select name="table_name" id="table_name" class="table_name db-export">
								<?php foreach($tableLists as $table){ ?>
                                <option value="<?php echo $table; ?>" selected="selected"><?php echo $table; ?></option>
                                <?php } ?>
                            </select>
                        </div>
                        
                        <div class="toggle-label">
                            <span class="label"><?php //echo $this->translator->translator('hotels_list_page_search_postcode'); ?></span>
                        </div>
                        
                        <div class="toggle-field">
                            <?php  if ($permission_arr['export_enable']) : ?>
                            <span class="button  ui-widget-content-1"><a href="javascript: void(0);" rel="db" class="export_btn"><span class="icon submit"><?php echo $this->translator->translator('common_export'); ?></span></a></span>
                            <?php endif; ?>
                        </div>
                 	</div>
                    <!-- Row 1 End -->
                    
                    
                    <!-- Row 2 Start -->
                    <div class="toggle-row">
                        <div class="toggle-label">
                            <span class="label"><?php echo $this->translator->translator('database_list_page_export_dynamic_form'); ?></span>
                        </div>
                        
                        <div class="toggle-field" style="vertical-align:middle;">
                           <select name="table_name" id="table_name" class="table_name db-export">
								<?php 
								if($formLists)
								{
									foreach($formLists as $key => $value)
									{ 
								?>
										<option value="<?php echo $key; ?>" <?php if($key < 2) { ?>selected="selected" <?php } ?>><?php echo $value; ?></option>
								<?php 
									}
								}
								?>
                            </select>
                        </div>
                        
                        <div class="toggle-label">
                            <span class="label"></span>
                        </div>
                        
                        <div class="toggle-field">
                            <?php  if ($permission_arr['export_enable']) : ?>
                            <span class="button  ui-widget-content-1"><a href="javascript: void(0);" rel="form" class="export_btn"><span class="icon submit"><?php echo $this->translator->translator('common_export'); ?></span></a></span>
                            <?php endif; ?>
                        </div>
                 	</div>
                    <!-- Row 2 End -->
                                       
                    
                    
				</div>
                <!--<hr />
                <div class="clr form-button-container">
                    <span class="button ui-widget-content-1"><a href="javascript: void(0);" class="search_btn"><span class="icon search"><?php //echo $this->translator->translator('prperty_list_page_search_button'); ?></span></a></span>
                </div>   -->     	
     	</div>
        
    	<div class="pagination">
        	<?php echo $this->paginationControl($this->datas, 'Sliding', 'top_pagination.phtml'); ?>
        </div>
        
        <div class="chart">
			<div class="data-table">
            	<table id="sortTable" width="100%" align="center" cellpadding="0" cellspacing="0">
                    <thead>
                    	<tr>
                          	<th width="4%" class="center"><input type="checkbox" name="checkAll" id="checkAll" class="checkAll_btn" /></th>
                          	<th width="87%"><?php echo $this->translator->translator('database_csv_list'); ?></th>
                         	<th width="9%"><?php echo $this->translator->translator('common_action'); ?></th>
                       	</tr>
                   	</thead>
                    <tbody>
                    <?php 
                    $j = 1;
                    foreach ($this->datas as $entry): 													
                        if($j % 2 == 0)
                        {
                            $onmouseout = "this.bgColor='#FFFFFF';";
                            $background = '#FFFFFF';
                        }
                        else
                        {
                            $onmouseout = "this.bgColor='#F7F7F7';";
                            $background = '#F7F7F7';
                        }																									
                    ?>
                   		<tr bgcolor="<?php echo $background; ?>" onmouseover="this.bgColor='#FCF5DD';" onmouseout="<?php echo $onmouseout; ?>">
                        	<td class="center checkbox"><input type="checkbox" name="checkbtn" id="checkbtn" value="<?php echo $this->escape($entry['name']); ?>" class="check_btn" /></td>
                          	<td><a href="<?php echo $this->serverUrl().$this->baseUrl().'/'.$this->escape($entry['path']).'/'.$this->escape($entry['name']); ?>" ><?php echo $this->escape($entry['name']); ?></a></td>												  
                          	<td class="tools-list">
                            	<ul>
                                	<li>
									<?php if ($permission_arr['import_enable']) : ?>
                                    <a href="javascript:void(0);" class="restore_btn"  rel="<?php echo $this->escape($entry['name']); ?>"><img src="application/modules/Administrator/layouts/scripts/images/tools/restore.png" title="<?php echo $this->translator->translator('common_restore'); ?>"  border="0" /></a>
                                    <?php endif; ?>
                                    </li>
                                    
                                  	<li>
									<?php if ($permission_arr['delete_enable']) : ?>
                                    <a href="javascript:void(0);" class="delete_btn"  rel="<?php echo $this->escape($entry['name']); ?>"><img src="application/modules/Administrator/layouts/scripts/images/tools/delete.png" title="<?php echo $this->translator->translator('common_delete_title'); ?>"  border="0" /></a>
                                    <?php endif; ?>
                                    </li>
                             	</ul>
                          	</td>
                       	</tr>
                    <?php 													
                        $j++;
                        endforeach;	
                  	?>
                 	</tbody>
				</table>
            </div>
      	</div>
        
        <div class="pagination">
        	<?php echo $this->paginationControl($this->datas, 'Sliding', 'pagination.phtml'); ?>
        </div>
  	</div>
</div>

<div id="dialog_msg" title="<?php echo $this->translator->translator('common_dialog_msg',$this->translator->translator('database_csv_page_name')); ?>"></div>
<div id="dialog-confirm" title="<?php echo $this->translator->translator('common_confirmation',$this->translator->translator('common_delete')); ?>"></div>	
<div id="restore-confirm" title="<?php echo $this->translator->translator('database_restore_confirm'); ?>"></div>

<div id="floatingbar">
	<h1><?php echo $this->translator->translator('database_csv_page_name'); ?></h1>
    
    <div class="button-container">    	
        <?php  if ($permission_arr['delete_enable']) : ?>
        <span class="button  ui-widget-content-1"><a href="javascript: void(0);" class="delete_all"><span class="icon delete"><?php echo html_entity_decode($this->translator->translator("common_delete_selected"), ENT_QUOTES, "UTF-8"); ?></span></a></span>
        <?php endif; ?>
    </div>
</div>
</div>
<?php endif; ?>